<template>
  <div class="news-container">
    <h2>新闻管理</h2>
    
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="新闻标题">
          <el-input v-model="searchForm.titleFuzzy" placeholder="请输入新闻标题" clearable />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchForm.authorName" placeholder="请输入作者" clearable />
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">发布新闻</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 新闻列表 -->
    <el-table :data="newsList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="title" label="新闻标题" />
      <el-table-column prop="authorName" label="作者" width="120" />
      <el-table-column prop="content" label="内容" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="发布时间" :formatter="formatDateTime" width="180" />
      <el-table-column prop="top" label="置顶" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.top ? 'danger' : 'info'">
            {{ scope.row.hot === 0 ? '否' : scope.row.hot === 1 ? '小热度' : scope.row.hot === 2 ? '中热度' : '大热度' }}
          </el-tag>
          <span v-if="scope.row.top" style="font-size: 12px; color: #999;">
            (热门级别: {{ scope.row.hot === 0 ? '否热门' : scope.row.hot === 1 ? '小热门' : scope.row.hot === 2 ? '中热门' : '大热门' }})
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            :type="scope.row.top ? 'warning' : 'success'" 
            size="small" 
            @click="handleToggleTop(scope.row)"
          >
            {{ scope.row.top ? '取消置顶' : '置顶' }}
          </el-button>
          <el-button 
            :type="scope.row.status === 1 ? 'warning' : 'success'" 
            size="small" 
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '下架' : '发布' }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新闻表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="newsForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="newsForm.title" />
        </el-form-item>
        <el-form-item label="新闻内容" prop="content">
          <el-input 
            type="textarea" 
            v-model="newsForm.content" 
            rows="6"
            placeholder="支持Markdown格式"
          />
        </el-form-item>
        <el-form-item label="新闻图片" prop="image">
          <el-input v-model="newsForm.image" placeholder="请输入图片地址" />
        </el-form-item>
        <el-form-item label="作者" prop="authorId">
          <el-select v-model="newsForm.authorId" placeholder="请选择作者">
            <el-option
              v-for="author in authorList"
              :key="author.id"
              :label="author.name"
              :value="author.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="newsForm.status">
            <el-radio :label="0">草稿</el-radio>
            <el-radio :label="1">发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-switch v-model="newsForm.top" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 列表数据
const newsList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 新增：作者列表
const authorList = ref([])

// 搜索表单
const searchForm = reactive({
  titleFuzzy: '',
  authorName: '',
  createdAtStart: '',  // 替换 timeRange
  createdAtEnd: ''     // 替换 timeRange
})

// 日期范围
const dateRange = ref([])

// 新闻表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
// 在 newsForm 中添加 authorId 字段
const newsForm = reactive({
  id: '',
  title: '',
  content: '',
  image: '',
  authorId: '', // 新增字段
  authorName: '', // 新增字段
  status: 0,
  top: false
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入新闻内容', trigger: 'blur' }],
  authorId: [{ required: true, message: '请选择作者', trigger: 'change' }] // 新增验证规则
}

// 处理日期变化
const handleDateChange = (val) => {
  if (val) {
    searchForm.createdAtStart = val[0]
    searchForm.createdAtEnd = val[1]
  } else {
    searchForm.createdAtStart = ''
    searchForm.createdAtEnd = ''
  }
}

// 加载新闻列表
const loadNews = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }

    const res = await axios.get('/news/admin/loadDataList', { params })
    if (res.data.status === 'success') {
      newsList.value = res.data.data.list
      total.value = res.data.data.totalCount
    }
  } catch (error) {
    console.error('获取新闻列表失败:', error)
    ElMessage.error('获取新闻列表失败')
  } finally {
    loading.value = false
  }
}

// 加载作者列表
const loadAuthors = async () => {
  try {
    const res = await axios.get('/user/loadDataList') // 修改请求路径
    if (res.data.status === 'success') {
      authorList.value = res.data.data.list.map(user => ({
        id: user.userId, // 修改字段名
        name: user.userRealName // 修改字段名
      }))
    }
  } catch (error) {
    console.error('获取作者列表失败:', error)
    ElMessage.error('获取作者列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadNews()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []  // 清空日期选择器
  currentPage.value = 1
  loadNews()
}

// 新增新闻
const handleAdd = () => {
  dialogTitle.value = '发布新闻'
  dialogVisible.value = true
  Object.keys(newsForm).forEach(key => {
    newsForm[key] = key === 'status' ? 0 : key === 'top' ? false : ''
  })
}

// 编辑新闻
const handleEdit = (row) => {
  dialogTitle.value = '编辑新闻'
  dialogVisible.value = true
  Object.keys(newsForm).forEach(key => {
    newsForm[key] = row[key]
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = newsForm.id ? '/news/updateNewsById' : '/news/admin/add'

        const res = await axios.post(url, {
          ...newsForm,
          authorName: authorList.value.find(author => author.id === newsForm.authorId)?.name // 确保 authorName 被包含在提交的数据中
        })
        if (res.data.status === 'success') {
          ElMessage.success(newsForm.id ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadNews()
        }
      } catch (error) {
        console.error(newsForm.id ? '更新新闻失败:' : '添加新闻失败:', error)
        ElMessage.error(newsForm.id ? '更新失败' : '添加失败')
      }
    }
  })
}

// 切换置顶状态
const handleToggleTop = async (row) => {
  try {
    const { value: hotLevel } = await ElMessageBox.prompt(
      `确定要${row.top ? '取消置顶' : '置顶'}该新闻吗？请选择热门级别：`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^(0|1|2|3)$/,
        inputErrorMessage: '热门级别必须是0, 1, 2, 或 3.(0-没热度/1-小热度/2-中热度/3-大热度)',
        inputValidator: (value) => {
          if (!value) {
            return '热门级别不能为空';
          }
          if (!/^(0|1|2|3)$/.test(value)) {
            return '热门级别必须是0, 1, 2, 或 3';
          }
          return true;
        }
      }
    )

    if (hotLevel !== undefined) {
      const res = await axios.post('/news/updateNewsById', {
        id: row.id,
        top: !row.top,
        hot: parseInt(hotLevel)
      })
      if (res.data.status === 'success') {
        ElMessage.success(row.top ? '取消置顶成功' : '置顶成功')
        loadNews()
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 切换发布状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '取消发布' : '发布'}该新闻吗？`, 
      '提示',
      { type: 'warning' }
    )
    const res = await axios.post('/news/updateNewsById', {
      id: row.id,
      status: row.status === 1 ? 0 : 1
    })
    if (res.data.status === 'success') {
      ElMessage.success(row.status === 1 ? '取消发布成功' : '发布成功')
      loadNews()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除新闻
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该新闻吗？', '提示', {
      type: 'warning'
    })
    const res = await axios.post('/news/deleteNewsById', {
      id: row.id
    })
    if (res.data.status === 'success') {
      ElMessage.success('删除成功')
      loadNews()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除新闻失败:', error)
      ElMessage.error('删除新闻失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 清理 ResizeObserver
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
    resizeObserver.value = null
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadNews()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadNews()
}

// 格式化时间
const formatDateTime = (row, column) => {
  return row[column.property] ? dayjs(row[column.property]).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 添加 ResizeObserver 实例
const resizeObserver = ref(null)

onMounted(() => {
  loadNews()
  loadAuthors() // 新增调用

  // 示例：假设有一个元素需要观察
  const element = document.querySelector('.some-element-to-observe')
  if (element) {
    resizeObserver.value = new ResizeObserver(entries => {
      for (let entry of entries) {
        console.log('Element size changed:', entry.contentRect)
      }
    })
    resizeObserver.value.observe(element)
  }
})

// 添加卸载时的清理逻辑
onUnmounted(() => {
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
  }
})

</script>

<style scoped>
.news-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  z-index: 1;
  position: relative;
}

:deep(.el-pagination) {
  margin: 0;
  padding: 0;
}
</style>